package com.biallen.datastructure.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PolishNotation {

    public static void main(String[] args) {
         String expression  ="1 8 + 2 1 + -";
        List<String> listString = getListString(expression);
        Stack<String> stack = new Stack();
        for (String s : listString) {
            if(s.matches("\\d+")){
                stack.push(s);
            }else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res  =0;
                if(s.equals("*")){
                    res= num1* num2;
                }else  if(s.equals("/")){
                    res= num1/num2;
                }else if(s.equals("+")){
                    res = num1+num2;
                }else  if(s.equals("-")){
                    res= num1-num2;
                }else {
                    throw  new RuntimeException("运算符有误!");
                }
                stack.push(res+"");

            }

        }
        System.out.println("计算结果:"+stack.pop());
    }

    public static List<String> getListString(String ex){

        String[] stArr = ex.split(" ");
        List<String> ls  = new ArrayList<String>();
        for (String s : stArr) {
            ls.add(s);
        }
        return  ls;
    }
}
